Page({
  data: {
    iphone: "",
    code: "",
    countDownVisible: false,
    nextlink: undefined
  },
  onLoad(option) {
    console.log(option)
    let { nextlink } = option
    this.setData({
      nextlink
    })
  },
  async getCode() {

    if (!this.data.iphone) {
      return wx.showToast({
        title: '手机号不能为空',
        icon: 'none'
      })
    }

    if (!/^1[0-9]{10}$/.test(this.data.iphone)) {
      return wx.showToast({
        title: '请填写正确的手机号',
        icon: 'none'
      })
    }

    let res = await wx.http.get('/code', { mobile: this.data.iphone })

    console.log(res)
    this.setData({
      countDownVisible: true
    })

  },
  async login() {

    if (!this.data.iphone) {
      return wx.showToast({
        title: '手机号不能为空',
        icon: 'none'
      })
    }

    if (!/^1[0-9]{10}$/.test(this.data.iphone)) {
      return wx.showToast({
        title: '请填写正确的手机号',
        icon: 'none'
      })
    }

    if (!/[0-9]{6}/.test(this.data.code)) {
      return wx.showToast({
        title: '请填写有效的6位验证码',
        icon: 'none'
      })
    }

    let res = await wx.http.post('/login',
      { mobile: this.data.iphone, code: this.data.code })

    let app = getApp()
    app.setToken('token', res.token)
    app.setToken('refreshToken', res.refreshToken)

    if (!this.data.nextlink) {
      wx.redirectTo({
        url: '/pages/index/index',
      })
    } else {
      wx.redirectTo({
        url: '/' + this.data.nextlink,
      })
    }

  },
  countDownChange(ev) {
    this.setData({
      timeData: ev.detail,
      countDownVisible: ev.detail.minutes === 1 || ev.detail.seconds > 0,
    })
  },
})
